﻿using FMusicReload.NetMusicNetwork;
using FMusicReload.Utils;
using FMusicReload.Views;
using HandyControl.Controls;
using HTBInject.Utils;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using MessageBox = System.Windows.MessageBox;

namespace FMusicReload
{
    public partial class MainWindow
    {
        private LogHelper lh = new LogHelper("MainWindow");
        public MainWindow()
        {
            InitializeComponent();
            nav.SelectedIndex = 0;
            Closed += (s, e) => Environment.Exit(0);

            HomeView.ToSwitchSearchView += (searchText) =>
            {
                SearchView.PassValue = searchText;
                nav.SelectedIndex = -1;
                LoadPageV3(typeof(SearchView));
                GC.Collect();
            };

            lh.SendLog("Interlize MainWindow Done!", LogHelper.LogType.Success);
            GC.Collect();
            InterlizeMusicPlayer();
            interlizeContextMenu1();

            MusicCoverImg.MouseDown += (s, e) =>
            {
                LoadPageV3(typeof(LyricPage));
            };

            Setting.ThemeSwitch += (s) => 
            { 
                controller.Background = StaticColorAssets.GetBasicColor();
                if (!(nav.SelectedIndex is -1))
                {
                    ((ListBoxItem)nav.SelectedItem).Background = StaticColorAssets.blue;
                    ((ListBoxItem)nav.SelectedItem).Foreground = StaticColorAssets.white;
                }
                foreach (ListBoxItem item in nav.Items)
                {
                    if (!item.Equals((ListBoxItem)nav.SelectedItem))
                    {
                        item.Foreground = StaticColorAssets.black;
                        item.Background = StaticColorAssets.none;
                    }
                }
                App.CollectRam();
            };
            controller.Background = StaticColorAssets.GetBasicColor();

            SearchView.PlayMusic += (music) =>
            {
                SearchResult sr = (SearchResult)music;
                MessageBox.Show(sr.id.ToString());
                PlayingList.AddMusic(new MusicItem(sr.Title, sr.id.ToString()));
                GC.Collect();
            };

            PlayList.Opened += (s, e) =>
            {
                PlayList_List.ItemsSource = PlayingList.GetModelDisplay();
            };

            PlayList_Delete.Click += (s, e) =>
            {
                if (PlayList_List.SelectedIndex is -1) return;
                PlayingList.MusicRemove(PlayList_List.SelectedIndex);
                Growl.SuccessGlobal("移除成功");
                PlayList_List.ItemsSource = PlayingList.GetModelDisplay();
            };

            PalyList_Play.Click += (s, e) =>
            {
                if (PlayList_List.SelectedIndex is -1) return;
                var muitem = PlayingList.Get(PlayList_List.SelectedIndex);
                if (muitem is null) return;
                var music = new GetMusicDetil(muitem.id);
                
                PlayMusic(music.url, muitem.Title, muitem.id);
                music.Dispose();
                GC.Collect();
            };

            PlayingList.AddMusic(new MusicItem("花の塔", "1956534872"));
        }

        private ContextList cl = new ContextList();
        public void interlizeContextMenu1()
        {
            var slider = new Slider() { Maximum = 1, Minimum = 0, Value = Mediaplayer.Volume};
            slider.ValueChanged += (s, e) =>
            {
                Mediaplayer.Volume = slider.Value;
            };
            cl.AddItem(new CtxItem(slider, "\ue767", GetType().GetMethod("Empty"), this));
            cl.AddItem(new CtxItem("播放列表", "\uea42", GetType().GetMethod("PlayListController"), this));
            PlayerPlayList.ContextMenu = cl.Build();
            GC.Collect();
        }

        public void Empty() { }

        public void PlayListController() => PlayList.IsOpen = !PlayList.IsOpen;

        #region 播放器
        private static MediaElement Mediaplayer = new MediaElement();
        private DispatcherTimer PlayerTimer;
        private bool IsNotDraging = true;
        public static object MusicDetil;
        public static bool MediaIsPlaying = false;
        public static MusicPlayList PlayingList { set; get; }

        public void InterlizeMusicPlayer()
        {
            Mediaplayer.MediaOpened += MediaPlayer_MediaOpened;
            Mediaplayer.MediaEnded += Mediaplayer_MediaEnded;
            Mediaplayer.MediaFailed += Mediaplayer_MediaFailed;
            Mediaplayer.LoadedBehavior = MediaState.Manual;

            PlayerPlayList.Click += (s, e) => PlayerPlayList.ContextMenu.IsOpen = true;

            PlayerPause.Click += (s,e) => {
                if (MediaIsPlaying)
                {
                    PlayerPause.Content = "\xE768";
                    Mediaplayer.Pause();
                }
                else
                {
                    if(Mediaplayer.Source is null)
                    {
                        var muitem = PlayingList.Get(0);
                        if (muitem is null) return;
                        var music = new GetMusicDetil(muitem.id);
                        
                        PlayMusic(music.url, muitem.Title, muitem.id);
                        music.Dispose();
                        GC.Collect();
                    }
                    PlayerPause.Content = "\xE769";
                    Mediaplayer.Play();
                }
                MediaIsPlaying = !MediaIsPlaying;
            };

            PlayerGoBack.Click += (s, e) =>
             {
                 var muitem = PlayingList.Back();
                 if (muitem is null) return;
                 var music = new GetMusicDetil(muitem.id);
                 
                 PlayMusic(music.url, muitem.Title, muitem.id);
                 music.Dispose();
                 GC.Collect();
             };

            PlayerGoNext.Click += (s, e) =>
            {
                var muitem = PlayingList.Next();
                if (muitem is null) return;
                var music = new GetMusicDetil(muitem.id);
                
                PlayMusic(music.url, muitem.Title, muitem.id);
                music.Dispose();
                GC.Collect();
            };

            MusicInfo.MouseDown += (s, e) => { };

            if (PlayingList is null)
                PlayingList = new MusicPlayList();

            controller.Children.Add(Mediaplayer);
            App.CollectRam();
        }

        public static bool IsEnd { set; get; } = false;

        public void PlayMusic(string MusicUrl, string Title, string musicID)
        {
            if(!(Mediaplayer.Source is null)) lyricEngine.KillEngine();
            var Music_Detil = new MusicDetil(musicID);
            MusicDetil = musicID;
            MusicInfo.Text = Title + "\n" + Music_Detil.Artist;
            MusicCoverImg.Source = new BitmapImage(new Uri(Music_Detil.CoverImg,UriKind.RelativeOrAbsolute));
            Mediaplayer.Source = new Uri(MusicUrl, UriKind.RelativeOrAbsolute);
            Mediaplayer.Play();
        }
        
        private void PlayerSliderController_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
        {
            IsNotDraging = false;
        }

        private void PlayerSliderController_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            Mediaplayer.Position = TimeSpan.FromSeconds(PlayerSliderController.Value);
            IsNotDraging = true;
        }

        private void Mediaplayer_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Growl.ErrorGlobal("播放器播放源失败 at " + e.Source + " is: " + e.ErrorException.Message);
            Mediaplayer.Stop();
            GC.Collect();
        }

        private void Mediaplayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            IsEnd = true;
            MediaIsPlaying = false;
            PlayerPause.Content = "\xE768";
            var muitem = PlayingList.Next();
            if (muitem is null) return;
            var music = new GetMusicDetil(muitem.id);
            
            PlayMusic(music.url, muitem.Title, muitem.id);
            music.Dispose();
            App.CollectRam();
        }

        public static MediaElement GetPlayer() { return Mediaplayer; }

        private void MediaPlayer_MediaOpened(object sender, EventArgs e)
        {
            IsEnd = false;
            MediaIsPlaying = true;
            PlayerPause.Content = "\xE769";
            PlayerSliderController.Maximum = Mediaplayer.NaturalDuration.TimeSpan.TotalSeconds;
            //if (IsCompect)
            PlayerTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            PlayerTimer.Tick += (s, ent) => 
            {
                if(IsNotDraging)
                    PlayerSliderController.Value = Mediaplayer.Position.TotalSeconds;
            };
            PlayerTimer.Start();
        }
        #endregion

        private void nav_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(nav.SelectedIndex is -1))
            {
                ((ListBoxItem)nav.SelectedItem).Background = StaticColorAssets.blue;
                ((ListBoxItem)nav.SelectedItem).Foreground = StaticColorAssets.white;
            }
            foreach (ListBoxItem item in nav.Items)
            {
                if (!item.Equals((ListBoxItem)nav.SelectedItem))
                {
                    item.Foreground = StaticColorAssets.black;
                    item.Background = StaticColorAssets.none;
                }
            }
            LoadPageV3Manger(nav.SelectedIndex);
            //LoadPageV2(nav.SelectedIndex);
            GC.Collect();
        }

        public void LoadPage(string path)
        {
            if (shower.CanGoBack) shower.RemoveBackEntry();
            shower.Source = new Uri(path, UriKind.Relative);
            GC.Collect();
        }

        public delegate void Switcher(object id);
        /// <summary>
        /// 切换页面前发出
        /// </summary>
        public static event Switcher onSwitcher;
        /// <summary>
        /// 切换完页面发出
        /// </summary>
        public static event Switcher onSwitch;
        private int pid = 0;
        private bool isAnimatedEnabled = true;

        [Obsolete]
        public void LoadPageV2(int pageid)
        {
            try
            {
                onSwitcher(pid);
                pid = pageid;
                onSwitch(pid);
            }
            catch (Exception) { }
            if (isAnimatedEnabled)
                return;
            //shower.Content = PagesLoader.AnimatedPage(pageid);
            else
                shower.Content = PagesLoader.GetPage(pageid);
            GC.Collect();
        }

        private void LoadPageV3Manger(int index)
        {
            switch (index)
            {
                case 0:
                    LoadPageV3(typeof(HomeView));
                    break;
                case 2:
                    LoadPageV3(typeof(PlayListView));
                    break;
                case 3:
                    LoadPageV3(typeof(Setting));
                    break;
            }
            App.CollectRam();
        }

        private void LoadPageV3(object Page)
        {
            shower.Content = null;
            object obj = Activator.CreateInstance((Type)Page, null);
            if (isAnimatedEnabled)
                shower.Content = PagesLoader.AnimatedPage((SimplePanel)obj);
            else
                shower.Content = (SimplePanel)obj;
            GC.Collect();
        }
    }

    public class MusicPlayList
    {
        private List<MusicItem> lists = new List<MusicItem>();
        private int playindex = 0;

        public MusicPlayList()
        {

        }

        public int GetAllIndex() { return lists.Count; }

        public int GetNowPlayingIndex() { return playindex; }

        public void ClearList() => lists.Clear();

        public MusicItem Back()
        {
            playindex--;
            if (lists.Count  == 0) return null;
            if (playindex < 0)
                playindex = lists.Count - 1;
            return lists[playindex];
        }

        public MusicItem Next()
        {
            playindex++;
            if (lists.Count == 0) return null;
            if (playindex > lists.Count - 1)
                playindex = 0;
            return lists[playindex];
        }

        public List<string> GetModelDisplay()
        {
            List<string> st = new List<string>();
            foreach (var item in lists)
                st.Add(item.Title);
            return st;
        }


        public void MusicRemove(int index) => lists.Remove(lists[index]);

        public MusicItem Get(int index) 
        {
            if (lists.Count is 0) return null;
            else return lists[index]; 
        }

        public void AddMusic(MusicItem mi) => lists.Add(mi);
    }

    public class MusicItem
    {
        public string Title;
        public Uri url;
        public Uri coverimg;
        public string[] auth;
        public string id;

        [Obsolete]
        public MusicItem(string title, object url, string cover)
        {
            Title = title;
            this.url = new Uri((string)url, UriKind.RelativeOrAbsolute);
            coverimg = new Uri(cover, UriKind.RelativeOrAbsolute);
        }

        [Obsolete]
        public MusicItem(string title, string MusicID, string cover)
        {
            Title = title;
            id = MusicID;
            coverimg = new Uri(cover, UriKind.RelativeOrAbsolute);
        }

        public MusicItem(string title, string MusicID)
        {
            Title = title;
            id = MusicID;
        }

        public MusicItem(string title, object url, Uri CoverUri)
        {
            Title = title;
            this.url = new Uri((string)url, UriKind.RelativeOrAbsolute);
            coverimg = CoverUri;
        }
    }
}
